package com.example.springboot_carlos.Controller;


import com.example.springboot_carlos.Util.DBUtil;
import com.example.springboot_carlos.entiy.Article;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@RestController
public class ArticleController {
    @RequestMapping("/writeArticle")
    public void writeArticle(HttpServletRequest request, HttpServletResponse response){
        String title = request.getParameter("title");
        String author =request.getParameter("author");
        String content= request.getParameter("content");
        Article article = new Article(title,author,content);
        try (Connection connection= DBUtil.getConnection();){
            if(useFull.isnull(article)){
                response.sendRedirect("/write_info_error.html");
                return;
            }
            int num = useFull.insertArticle(connection,article);
            if(num>0){
                response.sendRedirect("/write_success.html");
                return;
            }
            response.sendRedirect("/write_info_error.html");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    @RequestMapping("/findArticle")
    public void findArticle(HttpServletRequest request,HttpServletResponse response)  {
        String title_key=request.getParameter("title_key");
        String author_key=request.getParameter("author_key");
        String content_key=request.getParameter("content_key");
        Article article = new Article(title_key,author_key,content_key);
        try (Connection connection=DBUtil.getConnection()){
            if(Article.allNull(article)){
                response.sendRedirect("/find_info_error.html");
                return;
            }
            showResult(request,response,article);
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/createArticle")
    public void createArticle(HttpServletResponse response)  {

        String[] title=DataBaseController.randomUsername(100);
        String[] author=DataBaseController.randomNickname(100);
        String[] content = DataBaseController.randomContent(100);
        String sql="INSERT INTO articletest (title,author,content)  " +
                "VALUES(?,?,?)";
        try (Connection connection =DBUtil.getConnection()){
            PreparedStatement ps = connection.prepareStatement(sql);
            for(int i=0;i<100;i++){
                ps.setString(1,title[i]);
                ps.setString(2,author[i]);
                ps.setString(3,content[i]);
                ps.executeUpdate();
            }
            response.sendRedirect("/find_article.html");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/deleteArticle")
    public void deleteArticle(HttpServletResponse response){
        try {
            Connection connection=DBUtil.getConnection();
            Statement statement =connection.createStatement();
            String sql="DELETE FROM articletest";
            statement.execute(sql);
            sql="DROP TABLE articletest";
            statement.execute(sql);
            sql="CREATE TABLE articletest( " +
                    "id INT PRIMARY KEY AUTO_INCREMENT," +
                    "title VARCHAR(30)," +
                    "author VARCHAR(30)," +
                    "content VARCHAR(3000) " +
                    ")";
            statement.execute(sql);
            response.sendRedirect("/find_article.html");
        } catch (SQLException | IOException throwables) {
            throwables.printStackTrace();
        }
    }

    private void showResult(HttpServletRequest request,HttpServletResponse response,Article article){
        try (Connection connection = DBUtil.getConnection();){
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>查询结果</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>文章列表</h1>");
            pw.println("<table border=\"1\">");
            pw.println("<tr>");
            pw.println("<td>ID</td>");
            pw.println("<td>标题</td>");
            pw.println("<td>作者</td>");
            pw.println("<td>正文</td>");
            pw.println("</tr>");


            String sql="SELECT id,title,author,content,COUNT(*) sum   " +
                    "From articletest " +
                    "WHERE title LIKE  ? " +
                    "AND author LIKE ? " +
                    "AND content LIKE ? ";
            PreparedStatement ps = connection.prepareStatement(sql);

            String titleName = "%"+article.getTitle()+"%";
            String authorName = "%"+article.getAuthor()+"%";
            String contentName = "%"+article.getContent()+"%";
            ps.setString(1,titleName);
            ps.setString(2, authorName);
            ps.setString(3, contentName);
            ResultSet rs=ps.executeQuery();
            int id;
            int num;
            if(rs.next()){
                num=rs.getInt("sum");
            }else{
                num=0;
            }
            if(request.getParameter("id")==null||request.getParameter("id").isEmpty()){
                id=1;
            }else{
                id=Integer.parseInt(request.getParameter("id"));

            }
            sql="SELECT id,title,author,content   " +
                    "From articletest " +
                    "WHERE title LIKE  ? " +
                    "AND author LIKE ? " +
                    "AND content LIKE ? " +
                    "LIMIT ?,10";
            ps = connection.prepareStatement(sql);

            ps.setString(1,titleName);
            ps.setString(2, authorName);
            ps.setString(3, contentName);
            ps.setInt(4,id-1);
            rs=ps.executeQuery();
            if(id>num){
                response.sendRedirect("/have_no_data_fail.html");
                return;
            }
            while (rs.next()){
                pw.println("<tr>");
                pw.println("<td>"+rs.getString("id")+"</td>");
                pw.println("<td>"+rs.getString("title")+"</td>");
                pw.println("<td>"+rs.getString("author")+"</td>");
                pw.println("<td>"+rs.getString("content")+"</td>");
                pw.println("</tr>");
                id++;
            }

            pw.println("</table>");
            pw.println("<h5><a href='/findArticle/?id="+(id+10)+"&num="+num+"&title_key="+ article.getTitle()+
                       "&author_key="+article.getAuthor()+"&content_key="+article.getContent()+"'>下一页</a></h5>");
            pw.println("<h2><a href=\"/index.html\">返回首页</a></h2>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");


        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
    }

}
